package cn.lentme.demo.request.api

import android.util.Log
import cn.lentme.demo.BuildConfig
import cn.lentme.demo.app.App
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

object RetrofitClient {
    private const val TAG = "RetrofitClient"

    // RetrofitClient Module 基URL
    private const val BASE_URL = BuildConfig.baseUrl

    private val retrofits: HashMap<String, Retrofit> = HashMap()

    fun <S> getRetrofitClient(apiClass: Class<S>, url: String=""): S {
        val realUrl = if("" != url) url else BASE_URL
        Log.d(TAG, "realUrl ----------> $realUrl")
        if(!retrofits.containsKey(realUrl)) {
            val retrofit = Retrofit.Builder().run {
                baseUrl(realUrl)
                client(getOkHttpClient())
                // 这里需要继续改进，不一定都是JSON
                addConverterFactory(GsonConverterFactory.create())
                    .build()
            }
            retrofits[realUrl] = retrofit
        }
        return retrofits[realUrl]!!.create(apiClass)
    }

    private fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()

        val cacheFile = File(App.instance.cacheDir, "http_cache")
        val cache = Cache(cacheFile, 1024 * 1024 * 50)

        builder.run {
            cache(cache)
            connectTimeout(60, TimeUnit.SECONDS)
            readTimeout(60, TimeUnit.SECONDS)
            writeTimeout(60, TimeUnit.SECONDS)
            retryOnConnectionFailure(true)
        }

        return builder.build()
    }

}